<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-12-3
 * Time: 上午10:42
 * To change this template use File | Settings | File Templates.
 */

namespace pft\Prod;


class Sale {
    private $db;
    private $fid;
    const SALEID = 4;

    private $s;
    /**
     * @param $db mysql实例
     * @param $fid 分销商ID（会员表ID）
     */
    public function __construct($db, $fid)
    {
        $this->db = $db;
        $this->fid = $fid;
        $this->s = \SoapInit::GetSoapInside();
    }

    /**
     * 获取分销商可销售的产品ID
     *
     * @return array
     */
    public function GetProdsid()
    {
        $sql = "SELECT aid,pids,fid FROM pft_product_sale_list WHERE fid={$this->fid} AND status=0 AND pids<>''";
        $this->db->query($sql);
        while($r = $this->db->fetch_assoc()) {
            if($r['pids']=='A') {
                $all[] = $r['aid'];
            }
            else {
                $pids[] = $r['pids'];
            }
        }
        
        if(count($all)>0) {
            $sql_get_prods = "SELECT id FROM uu_products WHERE apply_did IN (". implode(',',$all).")";       
            $this->db->query($sql_get_prods);
            while($list = $this->db->fetch_assoc()) {
                // $pids[] = $list['pid'];
                $pids[] = $list['id'];
            }
        }
        return $pids;
    }
    
    public function GetProdsid_n($sid=NULL){
        $sid = ($sid) ? $sid : $this->fid;
        $sql = "SELECT aid,pids,fid FROM pft_product_sale_list WHERE fid=$sid AND status=0 AND pids<>''";
        $GLOBALS['le']->query($sql);
        while($r = $GLOBALS['le']->fetch_assoc()) {
            $r['pids']=='A' ? $all[] = $r['aid']:$pids[] = $r['pids'];
        }
        if(count($all)>0) {
            $sid_s = implode(',',$all);
            $sql_get_prods = "SELECT id FROM uu_products WHERE p_status=0 AND apply_did IN ($sid_s)";       
            $GLOBALS['le']->query($sql_get_prods);
            while($list = $GLOBALS['le']->fetch_assoc()) {
                $pids[] = $list['id'];
            }
        }
        return $pids;
    }

    /**
     * 获取分销产品转供应的产品
     */
    public function GetEvoluteProdsid($flag, $pid = 0)
    {
        $sql_get = <<<SQL
SELECT e.id,e.fid,e.pid,e.sid,e.sourceid,e.lvl,e.status,e.aids,e.active
FROM pft_p_apply_evolute e LEFT JOIN uu_products p ON p.id=e.pid
WHERE fid={$this->fid}
SQL;
        if ($pid) {
            $sql_get .= " AND p.id={$pid}";
        }

        $sql_get .= "AND p.apply_limit=1 AND p.p_status IN(0,2,3,4,5)";

        $this->db->query($sql_get);
        $epid_arr = array();
        $edatas = array();
        $sid_arr = array();
        while($r=$this->db->fetch_assoc()) {
            $edatas[]   = $r;
            $epid_arr[] = $r['pid'];
            $sid_arr[]  = $r['sid'];
        }
        switch($flag) {
            case 1:
                $ret = $edatas;
                break;
            case 2:
                $ret = $epid_arr;
                break;
            case 3:
                $ret = $sid_arr;
                break;
        }
        return $ret;
    }

    public function GetAllSaleProds()
    {
        $firstProds = $this->GetProdsid();//一手数据
        $secondProds = $this->GetEvoluteProdsid(2);//二手数据
        if(!count($firstProds)>0 && !count($secondProds)) {
            return 0;
        }
        elseif(!count($secondProds)) {
            return $firstProds;
        }
        elseif(!count($firstProds)) {
            return $secondProds;
        }
        else {
            return array_merge($firstProds, $secondProds);
        }
    }
    /**
     * 获取分销价格
     *
     * @param integer $tid 产品ID（pid）
     * @param integer $aid 上级供应商ID
     * @param bool $debug 是否打开调试
     * @return array $ret
     */
    public function GetPriceSet($tid=0, $aid=0,$debug=false)
    {
        $sql = "SELECT tid,dprice from uu_priceset "
            ."where pid={$this->fid} AND aid=$aid";
        if($tid>0) {
            $sql .= " AND tid=$tid";
        }
        $this->db->query($sql);
        if($debug) {
            echo $sql;
        }
        $ret = array();
        while($r = $this->db->fetch_assoc()) {
            $ret[$r['tid']] = $r['dprice'];
        }
        return $ret;
    }
    /**
     * 获取分销商可销售的产品数据
     *
     * @param Product $prod
     * @param \SoapClient $soap
     * @param int $count
     * @param int $limit
     * @param int $offset
     * @param null $title
     * @return null
     */
    public function GetProdsInfo(Product $prod, \SoapClient $soap, $count=0,
                                 $limit=0, $offset=20, $title=null)
    {
        $sales = $this->GetProdsid();
        if(!count($sales)) {
            return null;
        }
//        $aids = array_keys($sales);
        $str_pids = implode(',', $sales);
        $params = array('pids'=>$str_pids, 'limit'=>$limit, 'offset'=>$offset,
            'title'=>$title);
        $tickets = $prod->GetAllTicketList($params, $count);
        //如果是统计条数
        if($count==1) {
            return $tickets;
        }
        if(!count($tickets)) {
            return null;
        }
//        $fileter = array_filter($tickets, function($ticket) use($sales){
//            return ($sales[$ticket['apply_did']][0]=='A'
//                || in_array($ticket['pid'],$sales[$ticket['apply_did']]));
//        });
        $ret = $prod->format($tickets, $soap);
        return $ret;
    }

    /**
     *  查询会员可分销产品信息.
     *  @param $lid 景区id，默认不传，传入只返回改景区产品
     *  @return array 会员可分销产品，含直接供应和转供应产品
     *  @author 孙泽
     */
    public function salePros($lid=Null){
        $r=array();
        $salePids=array();
        $date = date("Y-m-d");
        $str="select tid,aid,dprice from uu_priceset where pid=".$this->fid;
        $this->db->query($str);
        while($row=$this->db->fetch_assoc()){
            $dprices[$row['tid']."_".$row['aid']]=$row['dprice'];
        }
        $sql="select p.id as pid,p.apply_did,p.p_status,l.id as lid,l.p_type,"
            ."l.title,l.area,l.topic,l.px,l.runtime,l.taobao_support,l.imgpath,"
            ."l.address,t.id as tid,t.pay,t.getaddr,t.title as ttitle,t.tprice"
            .",t.notes,t.buy_limit_low,t.ddays,t.delaydays,t.status,"
            ."f.ass_station,f.tourist_info,f.mdays,f.mhour,f.rdays "
            ."from uu_products p left join uu_land l on p.contact_id=l.id"
            ." left join uu_jq_ticket t on p.id=t.pid left join uu_land_f f"
            ." on f.pid=p.id";
        $where="where p.p_status in (0,3,4,5) and p.apply_limit=1";
        if ($lid) {
            $where .= " and l.id=$lid ";
        }
        $orderby=" order by l.px desc ";

        /*一手供应商产品*/
        $aids = array(0=>$this->fid);
        $str="select l.pids,l.aid from pft_product_sale_list l join ".
            "pft_member m on l.aid=m.id where l.fid={$this->fid} ".
            "and l.status=0 and m.status=0";
        $this->db->query($str);
        while($row=$this->db->fetch_assoc()){
            $salePids[$row['aid']] = explode(",",$row['pids']);
            $aids[] = $row['aid'];
        }
        if(count($aids)!=0){
            $aids=implode(",",$aids);
            $where1 = $where." and p.apply_did in ($aids) ";
            $str1 = "$sql $where1 $orderby";
            $this->db->query($str1);

            while($row = $this->db->fetch_assoc()){
//                print_r($row);
                if( $row['apply_did'] != $this->fid &&
                    $salePids[$row['apply_did']][0] != "A" &&
                    !in_array($row['pid'],$salePids[$row['apply_did']]) )
                {
                    continue;
                }
//                if(($row['jsprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date,1))==-1){
//                    $row['jsprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date,2);
//                }
//                if(($row['uprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date,1,"","",1))==-1){
//                    $row['uprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date,2,"","",1);
//                }
//                if($row['jsprice']==-1||$row['uprice']==-1) continue;
//                $row['jsprice']=$row['jsprice']+$dprices[$row['pid']."_0"];
//
                $row['sapply_did']=$row['apply_did'];
                $row['aid']=0;
                $row['lvl']=0;
                $r[]=$row;
            }
        }

        /*二手供应商产品*/
        $str="select * from pft_p_apply_evolute where fid=".$this->fid
            ." and status=0 and sid<>sourceid";
        $this->db->query($str);
        while($row=$this->db->fetch_assoc()){
            $secondInfo[$row['pid']."_".$row['sid']]=$row;
            $secondPids[]=$row['pid'];
        }
        if(count($secondPids)!=0){
//            $dprices2=array();
//            $str="select * from uu_priceset where tid in (".implode(",",$secondPids).")";
//            $this->db->query($str);
//            while($row=$this->db->fetch_assoc()){
//                $dprices2[$row['tid']."_".$row['pid']."_".$row['aid']]=$row['dprice'];
//            }
            $proInfo=array();
            $secondPids=implode(",",$secondPids);
            $where2=$where." and p.id in ($secondPids) ";
            $str2="$sql $where2 $orderby";
            $this->db->query($str2);
            while($row=$this->db->fetch_assoc()){
//                if(($row['jsprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date ,1))==-1){
//                    $row['jsprice']=$this->s->get_Dynamic_Price_Merge($row['pid'],$date,2);
//                }
//                if(($row['uprice']=$this->s->get_Dynamic_Price_Merge($row['pid'], $date,1,"","",1))==-1){
//                    $row['uprice']=$this->s->get_Dynamic_Price_Merge($row['pid'], $date,2,"","",1);
//                }
//                if($row['jsprice']==-1||$row['uprice']==-1) continue;
                $proInfo[$row['pid']]=$row;
            }
            foreach($secondInfo as $key=>$value){
                list($pid, $sapply_did) = explode("_",$key);

//                $key=explode("_",$key);
//                $pid=$key[0];
//                $sapply_did=$key[1];
                if(!$proInfo[$pid]) continue;
                $row=$proInfo[$pid];
                $row['sapply_did']=$sapply_did;
                $row['aid']=$sapply_did;
                $row['lvl']=$value['lvl'];
                $row['eid']=$value['id'];
                $row['estatus']=$value['status'];

                $aids=explode(",",$value['aids']);
                $aids[]=$value['fid'];
//                $count=count($aids);
                $aids[0]=0;
//                for($i=1;$i<$count;$i++){
//                    $row['jsprice']+=$dprices2[$row['pid']."_"
//                    .$aids[$i]."_".$aids[$i-1]];
//                }
                $r[]=$row;
            }
        }
        return $r;
    }

    /**
     * 获取分销商可销售的产品ID
     * @param int $pid      产品ID
     * @param int $lev      产品转分销等级，不能超过2级
     * @return array 可销售的产品ID
     *
     * */
    public function iCanSalePid($pid=0, $lev=null)
    {
        //二手销售数据
        $sql_get = <<<SQL
SELECT e.pid,e.sid FROM pft_p_apply_evolute e LEFT JOIN uu_products p ON p.id=e.pid
 WHERE e.fid={$this->fid} AND p.apply_limit=1 AND p.p_status IN(0,2,3,4,5)
SQL;
        if ( $pid ) {
            $sql_get .= " AND e.pid={$pid}";
        }
        if (!is_null($lev)) {
            $sql_get .= " AND e.lvl<$lev";
        }
        $this->db->query($sql_get);
        $epid_arr = array();
        $esid_arr = array();//供应商ID
        while($r=$GLOBALS['le']->fetch_assoc()) {
            $epid_arr[] = $r['pid'];
        }

        //一手供应的数据
        $pid_arr = $this->GetProdsid();
        if(!count($pid_arr) && count($epid_arr)>0) {
            $pid_arr = $epid_arr;
        }
        if(!count($pid_arr))  {
            return array();
        }
        $pid_str = implode(',', $pid_arr);
        //交换数组中的键和值
        $pids = array_flip(
            array_merge(explode(',', $pid_str),
                        array_keys($epid_arr)
            )
        ) ;
//        var_export($pids);
        $pids = array_keys($pids);
        sort($pids);
        return $pids;
    }
    public function iCanSalePidBeta($pid=0, $lev=null)
    {
        //二手销售数据
        $sql_get = <<<SQL
SELECT e.pid,e.sid FROM pft_p_apply_evolute e LEFT JOIN uu_products p ON p.id=e.pid
 WHERE e.fid={$this->fid} AND e.active=1 AND p.apply_limit=1 AND p.p_status IN(0,2,3,4,5)
SQL;
        if ( $pid ) {
            $sql_get .= " AND e.pid={$pid}";
        }
        if (!is_null($lev)) {
            $sql_get .= " AND e.lvl<$lev";
        }
        $this->db->query($sql_get);
        $epid_arr = array();
        $esid_arr = array();//供应商ID
        while($r=$GLOBALS['le']->fetch_assoc()) {
            $epid_arr[] = $r['pid'];
        }
//        print_r($epid_arr);
//        exit;
        //一手供应的数据
        $pid_arr = $this->GetProdsid();
        if(!count($pid_arr) && count($epid_arr)>0) {
            $pid_arr = $epid_arr;
        }
        if(!count($pid_arr))  {
            return array();
        }
//        print_r($pid_arr);
        $pid_str = implode(',', $pid_arr);

        //交换数组中的键和值
        $pids = array_flip(
            array_merge(explode(',', $pid_str),
                array_keys($epid_arr)
            )
        ) ;
//        var_export($pids);
        $pids = array_keys($pids);
        sort($pids);
        return $pids;
    }


    public function iCanSale($pid) {
        return in_array($pid, $this->iCanSalePid($pid));
    }

    /**
     * 套票下单检测
     *
     * @param \SoapClient $soap
     * @param int $pid 产品ID
     * @param int $memberId 下单人ID
     * @param int $aid 供应商ID
     * @param string $beginTime 游玩时间
     * @param int $tnum 预定数量
     * @return array
     */
    public static function PackageTicketCheck(\SoapClient $soap, $pid,
                                              $memberId, $aid, $beginTime,
                                              $tnum )
    {
//        print_r(func_get_args());
        $code     = $soap->PFT_Coupon_Pre_Check($pid, $memberId,$aid, $beginTime,
            $tnum);
//        echo $code;
        $pid      = 0;
        if ($code == 200) return array('code'=>200);
        if (strpos($code, '|') !== false) {
            $cs = explode('|', $code);
            $code = $cs[0];
            $pid  = $cs[1];
        }
        $arr = array(
            901=>'抱歉，无此套票，无法提交订单',
            902=>'抱歉，您没有权限购买该套票，无法提交订单',
            903=>'抱歉，您没有转分销该套票的权限',
            904=>'抱歉，此套票需提前预定，无法提交订单',
            905=>'抱歉，此套票被限定了具体的购买时间，无法提交订单',
            906=>'抱歉，此套票无此日期的价格，无法提交订单',
            907=>'抱歉，此套票日库存已不足，无法提交订单',//ok
            908=>'抱歉，此套票总库存已不足，无法提交订单',
            909=>'已经下架或不存在',//子票ok
            910=>'没有购买的权限',//子票ok
            911=>'转分销没有购买的权限',
            912=>'无此日期的价格',//ok
            913=>'日库存已不足',//ok
            914=>'总库存已不足',
            915=>'需提前预定',
            916=>'被限定了具体的购买时间',
        );
        return array('code'=>$code,'msg'=>$code.'-'.$arr[$code], 'pid'=>$pid);
    }

    /**
     * 套票下单检测
     *
     * @param $code 接口返回值
     * @return array|bool 成功：true,失败：array('msg'=>'', 'pid'=>产品id)
     */
    public static function PackageTicketChk($code)
    {

    }

}